import { warnTime } from './constant.js';
import IFileClient from './file_client_interface.js';
import request from '/@/utils/request.ts';
import FileIns from './file_instance.js';
import OSS from 'ali-oss';
export default class FileClient_Ali extends IFileClient {
	fileConfigs = null;
	OSS = null;
	bucket = null;
	setting = null;
	Expiration;
	constructor(fileConfig) {
		super(fileConfig);
		// console.log('ali setting', fileConfig)
		const that = this;
		this.bucket = fileConfig.Bucket;
		this.setting = fileConfig;
		this.Expiration = this.tc2beijing(this.setting.Expiration);
		this.isThekeyExpired();
		this.OSS = new OSS({
			region: that.setting.Region,
			accessKeyId: that.setting.AccessKeyId,
			accessKeySecret: that.setting.AccessKeySecret,
			bucket: that.setting.Bucket,
			stsToken: that.setting.Token,
		});
	}
	genFileConfig(fileConfigData) {
		const fileConfig = super.genFileConfig(fileConfigData);
		this.fileConfigs = fileConfig;
		if (fileConfig === null) {
			return null;
		}

		fileConfig.postData = {};

		return fileConfig;
	}

	isTokenExpired() {
		const { expiredTime } = this.m_fileConfig.postData;
		const nowTime = Math.floor(new Date().getTime() / 1000);
		return expiredTime - warnTime < nowTime;
	}

	async uploadContent(fileName, content) {
		console.log('wwwwwwwwwwwwwwwww', fileName, content);
		const afile = content;
		console.log('uploadRequest', afile, this.setting);
		let result;
		const date = new Date().getTime();
		const random = this.randomString();
		await this.isThekeyExpired();
		console.log('thisssssssssssss', this);
		if (fileName) {
			try {
				result = await this.OSS.multipartUpload('' + date + random + fileName, afile, {
					progress(p) {
						//获取进度条的值
						// console.log('progressprogress11111111', p * 100, cpt, res)
						if (vm) {
							vm.progressPercent.value = Number((p * 100).toFixed(2));
						}
					},
					// 设置并发上传的分片数量。
					parallel: 4,
					// 设置分片大小。默认值为1 MB，最小值为100 KB。
					partSize: 1024 * 1024,
				});
			} catch (err) {
				console.error('FileClient_Ali exception: ', err)
				if (err.name === 'InvalidAccessKeyIdError') {
					await this.isThekeyExpired();
					result = await this.OSS.multipartUpload('' + date + random + fileName, afile, {
						progress(p) {
							//获取进度条的值
							// console.log('progressprogress11111111', p * 100, cpt, res)
							if (vm) {
								vm.progressPercent.value = Number((p * 100).toFixed(2));
							}
						},
						// 设置并发上传的分片数量。
						parallel: 4,
						// 设置分片大小。默认值为1 MB，最小值为100 KB。
						partSize: 1024 * 1024,
					});
				}
			}
		} else {
			try {
				result = await this.OSS.multipartUpload(afile.uid + afile.name, afile, {
					progress(p) {
						//获取进度条的值
						// console.log('progressprogress11111111', p * 100, cpt, res)
						if (vm) {
							vm.progressPercent.value = Number((p * 100).toFixed(2));
						}
					},
					// 设置并发上传的分片数量。
					parallel: 4,
					// 设置分片大小。默认值为1 MB，最小值为100 KB。
					partSize: 1024 * 1024,
				});
			} catch (err) {
				console.error('FileClient_Ali exception: ', err)
				if (err.name === 'InvalidAccessKeyIdError') {
					await this.isThekeyExpired();
					result = await this.OSS.multipartUpload(afile.uid + afile.name, afile, {
						progress(p) {
							//获取进度条的值
							// console.log('progressprogress11111111', p * 100, cpt, res)
							if (vm) {
								vm.progressPercent.value = Number((p * 100).toFixed(2));
							}
						},
						// 设置并发上传的分片数量。
						parallel: 4,
						// 设置分片大小。默认值为1 MB，最小值为100 KB。
						partSize: 1024 * 1024,
					});
				}
			}
		}

		console.log('ali result', result);

		if (result.res.status === 200 && ![null, undefined, ''].includes(result.res.requestUrls[0])) {
			return this.formatFileUrl(result.res.requestUrls[0]);
		} else {
			return null;
		}
	}

	formatFileUrl(url) {
		if (url.indexOf('?uploadId') !== -1) {
			return url.substring(0, url.indexOf('?uploadId'));
		} else {
			return url;
		}
	}

	randomString() {
		const e = 5;
		var t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
			a = t.length,
			n = '';
		for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
		return n;
	}

	uploadFile(filePath) {
		const formData = new FormData();
		formData.append('file', filePath);
		request({
			url: this.fileConfigs.setting.uploadUrl,
			method: 'post',
			data: formData,
		});
	}

	getFileFullUrlArray(fileIDList, split) {
		return super.getFileFullUrlArray(fileIDList, split);
	}

	async isThekeyExpired() {
		let time = parseInt(new Date().getTime() / 1000);
		console.log('ali Expiration', this.Expiration, 'now time', time, 'be overdue?', this.Expiration < time);
		if (this.Expiration && this.Expiration < time) {
			localStorage.removeItem('setting');
			await FileIns.instance(null, false, true);
			this.Expiration = this.tc2beijing(this.setting.Expiration);
		}
	}

	async deleteFile(file) {
		console.log('ali deleteFile', file);
		await this.isThekeyExpired();
		if (file.url && !file.url.includes('blob')) {
			if (file.url.includes('http://')) {
				console.log('try delete tencent file');
				try {
					const fileName = file.url.substring(file.url.indexOf('.com/') + 5);
					console.log('delete fileName:', fileName);
					this.OSS.delete(fileName)
						.then((res) => {
							console.log('delete success:', res);
						})
						.catch((err) => {
							console.warn('delete err:', err);
						});
				} catch (error) {
					console.error('图片不存在', error);
				}
			}
		}
	}

	tc2beijing(utc_datetime) {
		// 转为正常的时间格式 年-月-日 时:分:秒
		var T_pos = utc_datetime.indexOf('T');
		var Z_pos = utc_datetime.indexOf('Z');
		var year_month_day = utc_datetime.substr(0, T_pos);
		var hour_minute_second = utc_datetime.substr(T_pos + 1, Z_pos - T_pos - 1);
		var new_datetime = year_month_day + ' ' + hour_minute_second;
		// 处理成为时间戳
		timestamp = new Date(Date.parse(new_datetime));
		timestamp = timestamp.getTime();
		timestamp = timestamp / 1000;
		// 增加8个小时，北京时间比utc时间多八个时区
		var timestamp = timestamp + 8 * 60 * 60;
		// 时间戳转为时间
		// var beijing_datetime = new Date(parseInt(timestamp) * 1000).toLocaleString().replace(/年|月/g, '-').replace(/日/g, ' ')
		return timestamp;
	}
}
